package com.abc.recycling.service.impl;

import com.abc.recycling.model.Collector;
import com.abc.recycling.repository.CollectorRepository;
import com.abc.recycling.service.CollectorService;
import com.abc.recycling.service.CollectorOrderService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.temporal.TemporalAdjusters;

@Service
@RequiredArgsConstructor
public class CollectorServiceImpl implements CollectorService {

    private final CollectorRepository collectorRepository;
    private final CollectorOrderService collectorOrderService;

    @Override
    public Collector getCurrentCollector() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return getCollectorByUsername(authentication.getName());
    }

    @Override
    @Transactional
    public void updateCollector(Collector collector) {
        if (collector == null || collector.getId() == null) {
            throw new IllegalArgumentException("回收员信息不能为空");
        }
        
        Collector existingCollector = getCollectorById(collector.getId());
        if (existingCollector == null) {
            throw new IllegalArgumentException("未找到指定回收员");
        }
        
        // 更新基本信息
        existingCollector.setRealName(collector.getRealName());
        existingCollector.setPhone(collector.getPhone());
        existingCollector.setEmail(collector.getEmail());
        existingCollector.setAddress(collector.getAddress());
        
        // 更新回收员特有信息
        existingCollector.setServiceArea(collector.getServiceArea());
        
        // 更新状态和时间
        if (collector.getStatus() != null) {
            existingCollector.setStatus(collector.getStatus());
        }
        existingCollector.setLastActiveTime(LocalDateTime.now());
        existingCollector.setUpdateTime(LocalDateTime.now());
        
        try {
            collectorRepository.save(existingCollector);
        } catch (Exception e) {
            throw new RuntimeException("更新回收员信息失败: " + e.getMessage());
        }
    }

    @Override
    public Collector getCollectorById(Long id) {
        return collectorRepository.findByIdAndRole(id, "COLLECTOR").orElse(null);
    }

    @Override
    public Collector getCollectorByUsername(String username) {
        return collectorRepository.findByUsernameAndRole(username, "COLLECTOR");
    }

    @Override
    @Transactional
    public void updateCollectorStatus(Long id, Integer status) {
        Collector collector = getCollectorById(id);
        if (collector != null) {
            collector.setStatus(status);
            collector.setLastActiveTime(LocalDateTime.now());
            collectorRepository.save(collector);
        }
    }

    @Override
    @Transactional
    public void updateCollectorRating(Long id, Double rating) {
        Collector collector = getCollectorById(id);
        if (collector != null) {
            collector.setAverageRating(rating);
            collectorRepository.save(collector);
        }
    }

    @Override
    @Transactional
    public void updateCollectorOrderStats(Long id) {
        Collector collector = getCollectorById(id);
        if (collector != null) {
            // 更新总订单数
            Long totalOrders = collectorOrderService.countOrdersByCollector(id);
            collector.setTotalOrders(totalOrders);

            // 更新本月订单数
            LocalDateTime now = LocalDateTime.now();
            LocalDateTime monthStart = now.with(TemporalAdjusters.firstDayOfMonth());
            Long monthlyOrders = collectorOrderService.countOrdersByCollectorAndDate(id, monthStart);
            collector.setMonthlyOrders(monthlyOrders);

            // 更新本月收入
            Double monthlyIncome = collectorOrderService.getCollectorMonthlyIncome(id);
            collector.setMonthlyIncome(monthlyIncome);

            // 更新最后活动时间
            collector.setLastActiveTime(LocalDateTime.now());

            collectorRepository.save(collector);
        }
    }
} 